﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Tzw.Common
{
    public class Secret
    {
        #region AES加密解密

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str">加密前明文内容</param>
        /// <param name="key">16位密钥</param>
        /// <returns></returns>
        public static string Encrypt_AES(string str, string key)
        {
            var keyArray = Encoding.UTF8.GetBytes(key);
            var toEncryptArray = Encoding.UTF8.GetBytes(str);

            var rDel = new System.Security.Cryptography.RijndaelManaged
            {
                Key = keyArray,
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            var cTransform = rDel.CreateEncryptor();
            var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str">密文内容</param>
        /// <param name="key">16位密钥<</param>
        /// <returns></returns>
        public static string Decrypt_AES(string str, string key)
        {
            var keyArray = Encoding.UTF8.GetBytes(key);
            var toEncryptArray = Convert.FromBase64String(str);

            var rDel = new System.Security.Cryptography.RijndaelManaged
            {
                Key = keyArray,
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            var cTransform = rDel.CreateDecryptor();
            var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Encoding.UTF8.GetString(resultArray);
        }

        #endregion

        #region MD5加密

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <returns></returns>
        public static string Encrypt_Md5(string txt)
        {
            using (var mi = MD5.Create())
            {
                var buffer = Encoding.Default.GetBytes(txt);
                var newBuffer = mi.ComputeHash(buffer);
                var sb = new StringBuilder();
                foreach (var t in newBuffer)
                {
                    sb.Append(t.ToString("x2"));
                }
                return sb.ToString().ToUpper();
            }
        }

        #endregion
    }
}